package com.gzsxy.config;

import com.gzsxy.entity.TPermission;
import com.gzsxy.entity.TUser;
import com.gzsxy.model.CustomUser;
import com.gzsxy.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaolong
 * @version 1.0
 * @description: springSecurity用户认证
 * @date 2021/11/2 20:46
 */
@Component
@Slf4j
public class MemberDetailsService  implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //1.登录的时候，调用该方法userName 查询账户是否存在，在验证账户的密码
        TUser tUser = userService.findByUsername(username);

        if(tUser == null){
            return null;
        }
        //2.在根据该账户的userid 查询该用户对应的权限
        List<TPermission> permissionList = userService.findPermissionByUsername(username);

        //绑定权限
        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        permissionList.forEach((a) ->{
            grantedAuthorities.add(new SimpleGrantedAuthority(a.getPermTag()));
        });

        log.info(">>permissionList:{}<<",permissionList);
        //设置权限
        String authPassword = new BCryptPasswordEncoder().encode(tUser.getPassword());

        //****一定要把权限存入进去，不然用户通过认证但没有权限，就算是下面通过父类去赋值了grantedAuthorities权限，
        // 但是最后返回的customUser是没有权限grantedAuthorities，然后把之前父类的覆盖掉了*****
        tUser.setAuthorities(grantedAuthorities);
//        //创建 security用户权限模型
        CustomUser customUser = new CustomUser(username,authPassword,grantedAuthorities);
//        //将tUser里面的属性值复制到customUser
        BeanUtils.copyProperties(tUser,customUser);

        return customUser;
    }
}
